package com.xhtt.modules.task.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.utils.CopyUtils;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.Query;
import com.xhtt.modules.cfg.entity.CfgTaskInfo;
import com.xhtt.modules.cfg.entity.CfgTaskSub;
import com.xhtt.modules.cfg.service.CfgTaskInfoService;
import com.xhtt.modules.cfg.service.CfgTaskSubService;
import com.xhtt.modules.sys.entity.SysUserEntity;
import com.xhtt.modules.task.dao.TaskServicePlanMapper;
import com.xhtt.modules.task.entity.TaskServicePlan;
import com.xhtt.modules.task.entity.TaskServiceTask;
import com.xhtt.modules.task.model.service.ArrangeModel;
import com.xhtt.modules.task.service.TaskServicePlanService;
import com.xhtt.modules.task.service.TaskServiceTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.xhtt.common.utils.SerialUtils.getSerialNo;

/**
 * <p>
 * 罐计划 服务实现类
 * </p>
 *
 * @author feipc
 * @since 2019-03-11
 */
@Service
public class TaskServicePlanServiceImpl extends ServiceImpl<TaskServicePlanMapper, TaskServicePlan> implements TaskServicePlanService {

    @Autowired
    private CfgTaskInfoService taskInfoService;
    @Autowired
    private CfgTaskSubService taskSubService;
    @Autowired
    private TaskServiceTaskService taskServiceTaskService;

    @Override
    public PageUtils planList(Map<String, Object> params, SysUserEntity user) {
        Object status = params.get("status");
        if (null != status && status.toString().equals("2"))//分配任务页面，执行班组的人可以看到安排给自己班组的任务，其他人看不到
        {
            if (null == user.getTeamId()) {//如果没有组的人 一条数据都看不见，那就给他设置一个不存在的teamid吧
                params.put("teamId", -100);
            } else {
                params.put("teamId", user.getTeamId());
            }
        }
        Page<TaskServicePlan> page = new Query<TaskServicePlan>(params).getPage();
        page.setRecords(baseMapper.planList(page, params));
        return new PageUtils(page);
    }

    @Override
    public void addPlan(TaskServicePlan taskServicePlan) {
        String noS = "CA" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        TaskServicePlan db = this.getOne(new LambdaQueryWrapper<TaskServicePlan>().likeRight(TaskServicePlan::getSerialNo, noS).orderByDesc(TaskServicePlan::getSerialNo));
        String serialNo = null == db ? "" : db.getSerialNo();
        noS = getSerialNo(noS, null == db, serialNo);
        taskServicePlan.setSerialNo(noS);
        taskServicePlan.setStatus(0);
        this.save(taskServicePlan);
    }

    @Override
    public void deletePlan(List<Integer> planIds) {
        this.removeByIds(planIds);
    }

    @Override
    public void updatePlan(TaskServicePlan taskServicePlan) {
        Integer planId = taskServicePlan.getId();
        if (null == planId) {
            throw new RRException("参数有误");
        }
        TaskServicePlan db = this.getById(planId);
        if (null == db) {
            throw new RRException("对象不存在");
        }
        CopyUtils.copyProperties(taskServicePlan, db);
        this.updateById(db);
    }

    @Override
    public TaskServicePlan getPlan(Integer planId) {
        return this.getById(planId);
    }

    @Override
    public void commitPlan(Integer planId) {
        TaskServicePlan servicePlan = this.getById(planId);
        if (null == servicePlan) {
            throw new RRException("对象不存在");
        }
        servicePlan.setStatus(1);//0待提交1待安排2待分配3退回4进行中9完成
        this.updateById(servicePlan);
    }

    @Override
    public ArrangeModel getArrangeInfo(Integer id) {
        ArrangeModel model = new ArrangeModel();
        TaskServicePlan taskServicePlan = this.getById(id);
        if (null == taskServicePlan) {
            throw new RRException("对象不存在");
        }

        model.setPlanId(id);
        model.setMainTaskName(taskServicePlan.getTaskName());
        //1清罐2管线清洗3洗罐4通球99其他
        String type = "";
        if (taskServicePlan.getType().intValue() == 1) {
            type = "维修需求";
        } else if (taskServicePlan.getType().intValue() == 2) {
            type = "维修确认";
        }
        CfgTaskInfo cfgTaskInfo = taskInfoService.getOne(new LambdaQueryWrapper<CfgTaskInfo>().eq(CfgTaskInfo::getName, type).select(CfgTaskInfo::getId));
        if (null == cfgTaskInfo) {
            throw new RRException("计划任务配置有误");
        }
        List<TaskServiceTask> tasks = new ArrayList<>();
        //找到配置好的要做的任务
        List<CfgTaskSub> taskSubList = taskSubService.list(new LambdaQueryWrapper<CfgTaskSub>().eq(CfgTaskSub::getTaskId, cfgTaskInfo.getId()));

        TaskServiceTask serviceTask;
        for (CfgTaskSub cfgTaskSub : taskSubList) {
            if (cfgTaskSub.getStatus().intValue() != 1) {
                continue;//删除状态的就不管
            }
            serviceTask = new TaskServiceTask();
            serviceTask.setName(cfgTaskSub.getName());
            serviceTask.setType(cfgTaskSub.getType());

            tasks.add(serviceTask);
        }
        model.setTasks(tasks);
        return model;
    }

    @Override
    @Transactional
    public void arrange(ArrangeModel arrangeModel) {
        Integer planId = arrangeModel.getPlanId();
        TaskServicePlan servicePlan = this.getById(planId);
        if (null == servicePlan) {
            throw new RRException("对象不存在");
        }
        servicePlan.setStatus(2);//0待提交1待安排2待分配3退回4进行中9完成
        servicePlan.setTaskName(arrangeModel.getMainTaskName());
        this.updateById(servicePlan);//跟新个名字而已
        //
        List<TaskServiceTask> tasks = arrangeModel.getTasks();
        tasks.forEach(taskServiceTask -> taskServiceTask.setServicePlanId(planId));

        //创建之前看一下有没有创建过了小任务 ，有的话全删除
        taskServiceTaskService.remove(new LambdaQueryWrapper<TaskServiceTask>().eq(TaskServiceTask::getServicePlanId, planId));
        taskServiceTaskService.saveBatch(tasks);//创建小任务
    }

    @Override
    public void back(TaskServicePlan plan) {
        TaskServicePlan sp = new TaskServicePlan();
        sp.setId(plan.getId());
        sp.setStatus(3);//1待安排2待分配3退回4进行中9完成
        sp.setBackReason(plan.getBackReason());
        this.updateById(sp);
    }
}
